package com.monitoring.application.service;

import com.monitoring.application.dto.SensorDTO;
import com.monitoring.domain.entity.Sensor;
import com.monitoring.domain.service.SensorService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class SensorApplicationService {
    private final SensorService sensorService;
    
    public SensorApplicationService(SensorService sensorService) {
        this.sensorService = sensorService;
    }
    
    // 创建传感器
    public SensorDTO createSensor(SensorDTO sensorDTO) {
        Sensor sensor = sensorService.createSensor(
                sensorDTO.getName(),
                sensorDTO.getLocation(),
                sensorDTO.getType()
        );
        return convertToDTO(sensor);
    }
    
    // 根据ID获取传感器
    public Optional<SensorDTO> getSensorById(Long id) {
        return sensorService.getSensorById(id)
                .map(this::convertToDTO);
    }
    
    // 获取所有传感器
    public List<SensorDTO> getAllSensors() {
        return sensorService.getAllSensors().stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }
    
    // 根据位置获取传感器
    public List<SensorDTO> getSensorsByLocation(String location) {
        return sensorService.getSensorsByLocation(location).stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }
    
    // 获取活跃的传感器
    public List<SensorDTO> getActiveSensors() {
        return sensorService.getActiveSensors().stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }
    
    // 更新传感器读数
    public void updateSensorReading(Long sensorId, double temperature, double humidity) {
        sensorService.updateSensorReading(sensorId, temperature, humidity);
    }
    
    // 激活传感器
    public SensorDTO activateSensor(Long id) {
        Sensor sensor = sensorService.activateSensor(id);
        return convertToDTO(sensor);
    }
    
    // 停用传感器
    public SensorDTO deactivateSensor(Long id) {
        Sensor sensor = sensorService.deactivateSensor(id);
        return convertToDTO(sensor);
    }
    
    // 删除传感器
    public void deleteSensor(Long id) {
        sensorService.deleteSensor(id);
    }
    
    // 转换实体到DTO
    private SensorDTO convertToDTO(Sensor sensor) {
        SensorDTO dto = new SensorDTO();
        dto.setId(sensor.getId());
        dto.setName(sensor.getName());
        dto.setLocation(sensor.getLocation());
        dto.setType(sensor.getType());
        dto.setActive(sensor.isActive());
        dto.setCreatedAt(sensor.getCreatedAt());
        dto.setUpdatedAt(sensor.getUpdatedAt());
        return dto;
    }
}